import axios from "axios";
/**进度条 */
import nProgress from "nprogress";
import "nprogress/nprogress.css";
/**elementplus消息弹框 */
import { ElMessage } from "element-plus";
/**取消请求 */
import { addPendingRequest, removePendingRequest } from "./cancel-repeat-request";
import router from "./router";
/**设置请求配置 */
export const server = axios.create({
  headers: {
    "Content-Type": "application/json;charset=utf-8",
    timeout: 10 * 1000,
  },
});
/**请求拦截器 */
server.interceptors.request.use(
  config => {
    config.url = `/api${config.url}`;
    removePendingRequest(config);
    addPendingRequest(config);
    nProgress.start();
    return config;
  },
  error => {
    throw new Error(error);
  }
);
/**响应拦截器 */
server.interceptors.response.use(
  response => {
    nProgress.done();
    removePendingRequest(response.config);
    if (response.status === 200 || response.status === 300) {
      return response.data;
    } else {
      ElMessage.error(response.data.msg || "数据异常");
    }
  },
  error => {
    ElMessage.info("系统繁忙");
    removePendingRequest(error.config || {});
    nProgress.done();
    throw new Error(error);
  }
);
